var map = new AMap.Map('container', {
        resizeEnable: true
    });
    AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：5s
            buttonPosition:'RB',    //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: false,   //定位成功后是否自动调整地图视野到定位点

        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function(status,result){
            if(status=='complete'){
                onComplete(result)
            }else{
                onError(result)
            }
        });
    });
    //解析定位结果
    function onComplete(data) {
//      document.getElementById('status').innerHTML='定位成功'
        var str = [];
        str.push('定位结果：' + data.position);
        str.push('定位类别：' + data.location_type);
        if(data.accuracy){
             str.push('精度：' + data.accuracy + ' 米');
        }//如为IP精确定位结果则没有精度信息
        str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
//      document.getElementById('result').innerHTML = str.join('<br>');
        console.log(data.position);
        fun(data.position);
    }
    //解析定位错误信息
//  function onError(data) {
////      document.getElementById('status').innerHTML='定位失败'
////      document.getElementById('result').innerHTML = '失败原因排查信息:'+data.message;
//  }
    //ajax
var arrJd = [];
var arrWd = [];
function jdwd(){
	$.ajax({
		type:"get",
		url:"json/data.json",
		async:false,
		success:function(res){
			console.log(res);
			for(i=0;i<res.length;i++){
				arrJd.push(res[i].JD);
				arrWd.push(res[i].WD);
			}
			var Res = JSON.stringify(res);
			sessionStorage.setItem("Arr",Res);
			console.log(arrJd);
			return arrJd,arrWd;
		}
	})
}
jdwd();
//arrJd = sessionStorage.getItem("Arr")
//arrJd = JSON.parse(arrJd);
console.log(arrJd);
console.log(arrWd);
function fun(x){
	console.log(x);
	var m1 = new AMap.Marker({
        map: map,
        draggable:true,
        position: new AMap.LngLat(x.lng,x.lat)
    });
    computeDis(m1);//把当前位置传进函数
}
var arrM = [];
 for(i = 0;i<arrWd.length;i++){
 	var m2 = new AMap.Marker({
        map: map,
        draggable:true,
        position:new AMap.LngLat(arrJd[i], arrWd[i])
    });
    arrM.push(m2.getPosition());//把所有门店的位置弄成一个数组
 }
 console.log(arrM);
 var arrDistance = [];
    function computeDis(mm){
    	for(i = 0;i<arrM.length;i++){
	        var p1 = mm.getPosition();
	        var p2 = arrM[i];
	        var textPos = p1.divideBy(2).add(p2.divideBy(2));
	        var distance = Math.round(p1.distance(p2));
	        arrDistance.push(distance);//把当前位置与所有门店的距离装成一个数组
	       }
    	 console.log(arrDistance);
    	 paixu(arrDistance);
    	}
//筛选出最近的门店
function paixu(arr){
	let Arr2 = [];
	for(x=0;x<arr.length;x++){
		Arr2.push(arr[x]);
	}
	console.log(Arr2);
	for(var i=0;i<arr.length;i++){
				for(var j=0;j<arr.length;j++){
					if(arr[i]<arr[j]){
						var x =arr[i];
						arr[i] =arr[j];
						arr[j] = x;
				}
					}
			}
	console.log(Arr2)
	console.log(arr);
	for(j=0;j<Arr2.length;j++){//找到最近距离的下标
    	 	if(Arr2[j]==arr[0]){
    	 		console.log(j);
    	 		var Res = sessionStorage.getItem("Arr",Res);
				Res = JSON.parse(Res);
				console.log(Res[j]);//打印最近门店的所有信息
				funStore(Res[j]);
    	 	}
    	 }
}
//渲染最近门店的路线及其他
function funStore(k){
	var lnglat = [k.JD, k.WD]; 
    var map = new AMap.Map('container', {
        resizeEnable: true,
        center: lnglat,
        zoom: 15
    });
    var marker = new AMap.Marker({
        position: lnglat
    });
    marker.setMap(map);

    var content = '<div class="info-title">'+k.shop_name+'</div><div class="info-content">' +
        '地址：'+k.address+'<br/>' +
        '电话：'+k.mobile+'</div>';
    var infowindow1 = new AMap.AdvancedInfoWindow({
        content: content,
        offset: new AMap.Pixel(0, -30),
    });
    infowindow1.open(map,lnglat);
    AMap.plugin('AMap.ToolBar',function(){//异步加载插件
        var toolbar = new AMap.ToolBar();
        map.addControl(toolbar);
    });
}
 